package com.aaa.Dao;

import com.aaa.Entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


/*
* 菜单管理实现类dao
* */
@Repository
public class MenuDao {
    private RowMapper<Menu> rowMapper = new RowMapper<Menu>() {
        public Menu mapRow(ResultSet resultSet, int i) throws SQLException {
            Menu menu = new Menu();
            menu.setId(resultSet.getLong("id"));
            menu.setName(resultSet.getString("name"));
            menu.setPath(resultSet.getString("path"));
            menu.setLev(resultSet.getInt("lev"));
            return menu; }
    };

    //根据角色id查询用户能操作的菜单
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<Menu> menuListById(Long uid){
        String sql ="select distinct m.* from users u inner join user_role ur on u.id=ur.u_id\n" +
                "                       inner join role r on ur.r_id=r.id\n" +
                "                       inner join role_menu rm on r.id=rm.r_id\n" +
                "                       inner join menu m on rm.m_id=m.id\n" +
                "                       where u.id=?";
        List<Menu> query = this.jdbcTemplate.query(sql, rowMapper, uid);
        return query;
    }
    //查询用户能操作的一级菜单
    public List<Menu> listOneMenus(Long uid){
        String sql ="select distinct m.* from users u inner join user_role ur on u.id=ur.u_id\n" +
                "                       inner join role r on ur.r_id=r.id\n" +
                "                       inner join role_menu rm on r.id=rm.r_id\n" +
                "                       inner join menu m on rm.m_id=m.id\n" +
                "                       where u.id=? and m.lev=1";
        List<Menu> query = this.jdbcTemplate.query(sql, rowMapper, uid);
        return query;
    }

    //查询用户能操作的某个一级菜单下的二级菜单
    public List<Menu> listTwoMenus(Long uid,Long pid){
        String sql ="select distinct m.* from users u inner join user_role ur on u.id=ur.u_id\n" +
                "                       inner join role r on ur.r_id=r.id\n" +
                "                       inner join role_menu rm on r.id=rm.r_id\n" +
                "                       inner join menu m on rm.m_id=m.id\n" +
                "                       where u.id=? and m.lev=2 and m.pid=?";
        List<Menu> query = this.jdbcTemplate.query(sql, rowMapper, uid,pid);
        return query;
    }
}
